<template>
  <div class="collectionchannel">
    <!--物模型配置 -->
     <div class="con"> 
         <div class="title-top">
              <span></span>
              <div class="mybtn" @click ="addChannel">新增配置</div>
         </div>
         <div class="mytable">
                <el-table :data="tableData" height="100%"  ref="mytable" stripe  style="width: 100%;" row-key="mykey"  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                                        <el-table-column type="index"  width="100" label="序号" align="center"> </el-table-column>
                                        <el-table-column prop="model_name" min-width="180" label="物模型名称"> </el-table-column>
                                        <el-table-column prop="key" min-width="180" label="key"> </el-table-column>
                                        <el-table-column prop="value" min-width="180" label="value"> </el-table-column>
                                        <el-table-column width="200" label="操作" fixed="right" align="center"> 
                                             <template  #default="{row}">
                                                    <div class="mysort">
                                                       <el-tooltip class="item" effect="dark" content="新增子级" placement="top">
                                                           <i class="el-icon-folder-add" style="font-size:16px" @click="addRecord(row)"></i>
                                                        </el-tooltip>
                                                       <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                                                           <img src="../../assets/btnImg/edit2.png" alt="" style="margin:0px 20px" @click.stop="editfn(row)">
                                                        </el-tooltip>
                                                         <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                                            <img src="../../assets/btnImg/del2.png" alt="" @click.stop="deletefn(row)">
                                                        </el-tooltip>  
                                                    </div>
                                                </template>
                                        </el-table-column>
               </el-table>
         </div>
           <!-- 新增/修改 -->
           <el-dialog width="950px" draggable  :title="caozuoType" :close-on-click-modal='false' v-model="addeditflagline">
                    <div class="choicedio">
                        <!-- MQTT客户端 -->
                        <div class="body-items">
                           <div class="infoitems">
                             <div class="items itemright">
                                <div class="leftname">物模型名称：</div>
                                <el-input v-model="model_name" placeholder="请输入物模型名称"></el-input>
                            </div>
                             <div class="items itemright">
                            </div>
                            
                            <div class="items">
                            </div>
                         </div>
                        </div>
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                      <template #footer>
                                 <div class="dialog-footer">
                                  <el-button  @click="addeditflagline = false" >取 消</el-button>
                            <el-button  class="last-el-button" @click="addpassageway" type="primary">确 定</el-button>
                                 </div>
                    </template>
                   
                      
                    
           </el-dialog>
           <!-- 新增/修改 物模型记录-->
           <el-dialog width="950px" draggable  :title="caozuoType2" :close-on-click-modal='false' v-model="recordFlag">
                    <div class="choicedio">
                        <!-- MQTT客户端 -->
                        <div class="body-items">
                           <div class="infoitems">
                             <div class="items itemright">
                                <div class="leftname">key：</div>
                                <el-input v-model="temp.key"></el-input>
                            </div>
                             <div class="items itemright">
                              <div class="leftname">value：</div>
                                <el-input v-model="temp.value"></el-input>
                            </div>
                            
                            <div class="items">
                            </div>
                         </div>
                        </div>
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                      <template #footer>
                                 <div class="dialog-footer">
                                  <el-button  @click="recordFlag = false" >取 消</el-button>
                            <el-button  class="last-el-button" @click="recordFn" type="primary">确 定</el-button>
                                 </div>
                    </template>
                   
                      
                    
           </el-dialog>
          <div class="el-loading-mask" v-show="isMask">
             <div class="el-loading-spinner"><svg viewBox="25 25 50 50" class="circular"> <circle cx="50" cy="50" r="20" fill="none" class="path"></circle></svg></div>
          </div>
     </div>
  </div>
</template>

<script>
import {getModelLists,saveModelLists,editModelLists,delModelLists,getModelRecord,saveModelRecord,editModelRecord,delModelRecord} from "../../api/Interface";
export default {

  data() {
    return {
      addeditflagline:false,//新增修改弹窗
      recordFlag:false,//新增修改弹窗
      diaisMask:false,//弹窗的缓冲
      gudingchannel_number:"",
      rightname:"",
      tableData:[],
      tableDataCopy:[],
      radio:"1",
      checked:true,
      isMask:false,
      input:"",
      protocolList:[],
      //表格选中
      nowTableRow:{},
      nowChangnow:false,
      caozuoType:"新增配置",
      caozuoType2:"新增物模型记录",
      deviceArrAll:[],//全部设备
      options:[],
      model_name:"",
      temp:{
        key:"",
        value:""
      },
      mynumkey:1,
    };
  },

  mounted() {
     this.getListAll()

  },
  watch:{
  },

  methods: {
    
    //新增通道编辑
    addChannel() {
      //   request({url: "http://192.168.124.17:19000/registration/verify",method: "get"}).then(res => { 
      //    if(res.code == 200 && res.data == true) {//验证成功
      //       this.$message({
      //         showClose: true,
      //         message: "注册成功",
      //         type: "success",
      //       });
            
      //    }else{//验证失败
      //        this.$message({
      //         showClose: true,
      //         message: "注册失败",
      //         type: "error",
      //       });
      //     }
      //  }).catch(() => {
      //  })
      //   return
        this.model_name = ""
        this.caozuoType = '新增配置'
        this.addeditflagline = true
    },
    //获取表格列表
    getListAll(){
      
      this.isMask = true
       this.recordFlag = false
       this.mynumkey = 1
        getModelLists().then(res => {
         this.isMask = false
        //  console.log("channel_protocolZhuan",this.protocolList);
         if(res == ""){
             this.tableData = []
         }else {
             var guiyueArr = []
             res.forEach(item => {
              this.mynumkey++
              item.mykey =  this.mynumkey
              // item.hasChildren = true
             })
             this.tableDataCopy = JSON.parse(JSON.stringify(res))
             this.tableData = res
             
            //  hasChildren: true
            this.getRecordList()
          // console.log("获取表格列表",this.tableData);
         }
          
        })
    },
    //新增修改通道
    addpassageway(){
        if(this.model_name === ""){
            this.$message({showClose: true,message: '物模型名称不能为空',type: 'warning'});
            return
        }
        var d = {
          model_name:this.model_name,
        }
      
      if(this.caozuoType == '新增配置'){//新增
          this.diaisMask = true
          saveModelLists(d).then(res => {
            // console.log("新增通道",res);
            this.diaisMask = false
            if(res != undefined){
                 this.getListAll()
                 this.addeditflagline = false
                  this.$message({showClose: true,message: '新增成功',type: 'success'});
            }else {
                this.$message({showClose: true,message: '新增失败',type: 'error'});
            }
          })
      }else {
        
         this.diaisMask = true
        d.id = this.nowTableRow.id
           editModelLists(d).then(res => {
            this.diaisMask = false
            // console.log("更新通道",res);
            if(res != undefined){
                 this.addeditflagline = false
                  this.$message({showClose: true,message: '更新成功',type: 'success'});
                  this.getListAll()
            }else {
                this.$message({showClose: true,message: '更新失败',type: 'error'});
            }
          })
      }
      
      
    },
    //修改配置
    editfn(row){
        this.model_name = row.model_name
        this.caozuoType = '修改配置'
         this.nowTableRow = row
        this.addeditflagline = true
    },
    //删除通道
    deletefn(row){
        this.$confirm(`是否要删除此配置？`,'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
               delModelLists({'id':row.id}).then(res => {
                  // console.log("删除",res);
                  if(res == undefined){
                     this.$message.error('删除失败！！')
                  }else {
                    this.getListAll()
                     this.$message({showClose: true,message: '删除成功',type: 'success'});
                  }
               }).catch(error => {
                    this.$message.error('删除失败！！')
               })    
            }).catch(() => {
              // ...
            });
    },
    //新增物模型记录
    addRecord(row){
      //  console.log("新增物模型",row);
       this.nowTableRow = row
       this.caozuoType2 = '新增物模型记录'
       this.temp = {
        key:"",
        value:""
      }
      // this.getRecordList()
      this.recordFlag = true
    },
    //查询物模型记录
    getRecordList(){
      function buildTree(items, parentId = 0) {
        return items
          .filter(item => item.parent_id === parentId)
          .map(item => ({
            ...item,
            children: buildTree(items, item.id)
          }));
      }
      getModelRecord().then(res => {
          var diyiArr = []//先把modelId相同的放同一数组
          if(res != undefined){
            this.tableData = []
             var modelId = []
             res.forEach(item => {
                 modelId.push(item.model_id)
             })
             var modelIdArr = [...new Set(modelId)]
             
             modelIdArr.forEach((item,index) => {
               diyiArr.push({
                 '物模型ID':item,
                 'allArr':[]
               })
               res.forEach(tt => {
                  if(tt.model_id == item){
                    diyiArr[index].allArr.push(tt)
                  }
               })
             })
             //然后把里面的组成一个树形结构
             diyiArr.forEach(item => {
                item.children = buildTree(item.allArr)
             })
             //每一项赋值一个唯一值
             var mykey = this.mynumkey
             var recursiveFunction=function() {
                const getStr=function(list) {
                  list.forEach(function(row) {
                    if(row.children.length!=0) {
                      mykey++
                      row.mykey = mykey
                      getStr(row.children)
                    } else {
                      mykey++
                      row.mykey = mykey
                      
                    }
                  })
                }
                getStr(diyiArr)
              }
              recursiveFunction()
             console.log("diyiArr",diyiArr);
             this.tableDataCopy.forEach(item => {
                item.children = diyiArr.filter(tt => tt['物模型ID'] == item.id)[0].children
             })
             this.tableData = JSON.parse(JSON.stringify(this.tableDataCopy))

          }
      })
    },
    //确定新增/修改物模型记录
    recordFn(){
        // if(this.model_name === ""){
        //     this.$message({showClose: true,message: '物模型名称不能为空',type: 'warning'});
        //     return
        // }
        var d = {
          model_id:this.nowTableRow.id,
          key:this.temp.key,
          value:this.temp.value,
          parent_id:0
        }
      
      if(this.caozuoType2 == '新增物模型记录'){//新增
          if (this.nowTableRow.hasOwnProperty('parent_id')) {
            d.parent_id = this.nowTableRow.id
            d.model_id = this.nowTableRow.model_id
          } 
          this.diaisMask = true
          saveModelRecord(d).then(res => {
            // console.log("新增通道",res);
            this.diaisMask = false
            if(res != undefined){
                 this.getListAll()
                 this.addeditflagline = false
                  this.$message({showClose: true,message: '新增成功',type: 'success'});
            }else {
                this.$message({showClose: true,message: '新增失败',type: 'error'});
            }
          })
      }else {
        
         this.diaisMask = true
         d.id = this.nowTableRow.id
           editModelRecord(d).then(res => {
            this.diaisMask = false
            // console.log("更新通道",res);
            if(res != undefined){
                 this.addeditflagline = false
                  this.$message({showClose: true,message: '更新成功',type: 'success'});
                  this.getListAll()
            }else {
                this.$message({showClose: true,message: '更新失败',type: 'error'});
            }
          })
      }
      
      
    },

    
    
  },
  filters: {
      // 转换时间戳
      "date_format": function(value) { //value就是插值的数据
        if(!value) {
          return ""
        }
        return value
      },
    }
};
</script>
<style lang="scss" scoped>
    
    .collectionchannel {
         width: 100%;
         height: 100%;
         position: relative;
         .con {
             width: 100%;
             height: 100%;
             background-color: #fff;
            //  padding: 12px;
             box-sizing: border-box;
           .title-top {
             width: 100%;
             height: 42px;
             display: flex;
             align-items: center;
             justify-content: space-between;
             border-bottom: 1px solid #E6E6E6;
             padding: 0px 12px;
             box-sizing: border-box;
             span {
                 font-size: 14px;
                 color: #1A1A1A;
             }
             
           }
           .mytable {
              width: 100%;
              height: calc(100% - 80px);
              padding: 0px 12px;
              box-sizing: border-box;
              margin-top: 12px;
              .mysort {
                 display: flex;
                 align-items: center;
                 justify-content: center;
              }
              .mysort-text {
               color:#2178F1;
              }
           }
          
        }
    }
    .infoitems {
       display: flex;
       align-items: center;
       .items {
         width: 50%;
       }
       .itemright {
         margin-right: 20px;
       }
       
    }
    .body-items {
      margin-top: 10px;
      .infoitems {
        .items {
              width: 33%;
              .leftname {
                     width: 80px;
                    min-width: 80px;
              }
          }
      }
           
       }
</style>